<template>
  <!--
   商品属性-->
  <div>
    商品规格:
    <el-card class="box-card">
      <div v-for="item in specs" :key="item.id" class="text item">
        <el-form>
          <el-form-item :label="item.name" prop="saleService">
            <el-checkbox-group v-model="checkdName" @change="addTableColumn()">
              <el-checkbox
                v-for="(option,index) in item.checkList"
                :key="index"
                :label="option"
              >{{option}}</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
      <el-button @click="addTableColumn()">新增</el-button>
      <el-button @click="dropTableData()">表格清空</el-button>
    </el-card>

    <el-card class="box-card">
      <el-table :data="tableData" border style="width: 100%">
        <el-table-column
          :prop="column.prop"
          :label="column.label"
          width="180"
          v-for="(column,index) in columns"
          :key="index"
        ></el-table-column>
        <el-table-column prop="price" label="* 销售价格" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.price"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="* 商品库存" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.num"></el-input>
          </template>
        </el-table-column>
        <el-table-column prop="alertNum" label="* 库存预警值" width="180">
          <template slot-scope="scope">
            <el-input v-model="scope.row.alertNum"></el-input>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="name" label="* SKU编号" width="180"></el-table-column> -->
        <el-table-column prop="address" label="* 操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="deletedTableData(scope.$index, scope.row)"
            >删除</el-button>
            <el-button
              type="primary"
              size="mini"
              @click="uploadPictures(scope.$index, scope.row)"
            >上传图片</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--
      商品参数-->
    <el-card>
      <el-table :data="paras" border style="width: 100%">
        <el-table-column prop="name" label="* 参数类型" width="180"></el-table-column>
        <el-table-column label="* 录入参数" width="180" prop="option">
          <template slot-scope="scope">
            <el-select v-model="editData[ scope.row.name ]" placeholder=" 请选择">
              <el-option
                v-for="(item,index) in scope.row.checkList"
                :key="index"
                :label="item"
                :value="item"
              ></el-option>
            </el-select>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!--商品图片-->
    <el-card class="box-card" body-style="height:400px">
      商品相册
      <br />
      <el-button @click="openSpuImage()">上传图片</el-button>
      <el-button  @click="tests">从图片库选择</el-button>
      <div class="demo-image__placeholder" v-for="(spuImageUrl,index) in spuImageUrls" :key="index">
        <div class="block">
          <div class="hwtDiv" style="margin-right:20px">
            <el-image :src="spuImageUrl" style="height:200px"></el-image>
            <el-button type="primary" v-if="index === 0">商品主图</el-button>
            <el-button type="primary" v-else @click="setZhuTu(index)" style="margin-right:10px">设为主图</el-button>
            <el-button type="primary" @click="deletedSpuImage(index)">删除图片</el-button>
          </div>
        </div>
      </div>
    </el-card>

    <Editor></Editor>

    <el-button type="primary" @click="topStep()">上一步，填写商品信息</el-button>
    <el-button @click="onSubmit()">提交审核</el-button>

    <!--表格sku图片上传对话框-->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
      <el-form>
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input v-model="ruleForm.name" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="属性图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:88/api/oss/upload/oss?folder=myimages&classify=brand"
            :show-file-list="false"
            :on-success="handleAvatarSuccess1"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="skuImageUrl" :src="skuImageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="saveImg">确 定</el-button>
      </span>
    </el-dialog>

    <!--商品spu图片模态框-->
    <el-dialog title="提示" :visible.sync="spuDialogVisible" width="30%" :before-close="handleClose2">
      <el-form>
        <el-form-item label="商品图片" :label-width="formLabelWidth">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:88/api/oss/upload/oss?folder=myimages&classify=brand"
            :show-file-list="false"
            :on-success="handleAvatarSuccess2"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="spuImageUrl" :src="skuImageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose2">取 消</el-button>
        <el-button type="primary" @click="saveSpuImg">确 定</el-button>
      </span>
    </el-dialog>
   <!-- 图库图片 -->
    <el-dialog title="贤" :visible.sync="dialogFormVisible3" :before-close="dc">
        <div>
          <div style="border-bottom:1px solid black;padding-bottom:50px;">
            <span style="float:left;">商品图库 > {{xian}}</span>
            <el-select  v-model="valueX" placeholder="请选择" style="float:right;margin-top:-10px;" @change="xianChange">
                <el-option
                    v-for="item in titleList2"
                    :key="item"
                    :label="item"
                    :value="item"
                    >
                    </el-option>
                </el-select>
          </div>
              <div style="border-bottom:1px solid black;padding-bottom:15px;">
                      <el-row>
                      <el-col :span="widths" v-for="(o, index) in tableData2" :key="index"  class="s51">
                          <el-card :body-style="{ padding: '0px' }">
                                <el-checkbox-group v-model="checkList2" style="float:left;" @change="zhangq">
                                  <el-checkbox :label="o.url" :key="index"><span> </span></el-checkbox>
                                </el-checkbox-group>
                          <img :src="o.url" class="image" style="float:left;">
                          </el-card>
                      </el-col>
                  </el-row>
              </div>
            <el-pagination
                class="header_right"
                @current-change="handleCurrentChange2"
                :current-page="currentPage2"
                :page-size="10"
                layout="prev, pager, next, jumper"
                :total="total2"
                ></el-pagination>
          </div>
          <div slot="footer" class="dialog-footer">
            <span style="float:left;">已选中{{zhang}}</span>
            <el-button @click="dialogFormVisible3 = false;valueX='';xian='全部图片';checkList2=[];zhang=0">取 消</el-button>
            <el-button type="primary" @click="save3">确 定</el-button>
          </div>
    </el-dialog>
  </div>
</template>

<script>
import Editor from '@tinymce/tinymce-vue'
export default {
  components: {
    Editor
  },
  props: {
    ruleForm: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
        currentPage2: 1,
        total2: 0,
        zhang: 0,
        valueX: '',
        xian: '全部图片',
        widths: 3,
        dialogFormVisible3: false,
      src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      editData: {},
      data: this.ruleForm,
      specs: [],
      paras: [], // 参数集合
      checkdName: [],
      tableData: [],
      columns: [],
      options: [], // 参数集合 按一个name一个集合分, [{name:[]}] //这样的格式
      ary: [], // 用来计算  计算笛卡尔积的数组
      hwtList: [], // 往ary添加被计算的数组
      myary: [],
      step3Form: {
        price: 1,
        num: 1,
        alertNum: 1
      },
      dialogVisible: false,
      formLabelWidth: "150px",
      skuImageUrl: '',
      skuImageUrls: [],
      sku: {},
      skus: [],
      skuData: [],
      columns2: [],
      options2: [],
      paraItems: '',
      specItems: {},
      spuImageUrl: '',
      spuImageUrls: [],
      spuDialogVisible: false,
      tableData2: [],
      checkList2: [],
      titleList2: ['全部图片']
    }
  },
  tagAll () {
    this.loading = true;
    this.tagAll().then(response => {
      if (response.ret === 0) {
        response.data.forEach((item, index) => {
          this.$set(this.editData, index, [])
        });
        this.tagAllDate = response.data;
      } else {
        this.$message.error(response.res_info);
      }
      this.loading = false
    })
  },
  methods: {
    async handleCurrentChange2(val) {
      this.currentPage2 = val;
      this.xianChange();
    },
      dc() {
          this.zhang = 0
          this.dialogFormVisible3 = false
          this.checkList2 = []
      },
      zhangq() {
          this.zhang = this.checkList2.length
      },
      save3() {
          if (this.checkList2.length === 0) {
          this.$message('未选择图片!');
          return null;
          }
          console.log(this.checkList2)
          this.checkList2.forEach(element => {
              this.spuImageUrls.push(element)
            });
          this.dialogFormVisible3 = false
          this.checkList2 = []
          this.valueX = ''
          this.xian = '全部图片'
          this.zhang = 0
      },
      async getXianTitle() {
            const { data: res2 } = await this.$http.get(`goods/album/findAll`)
            res2.data.forEach(element => {
              this.titleList2.push(element.title)
            });
      },
      async xianChange() {
        this.xian = this.valueX
        this.tableData2 = []
        // this.checkList2 = []
        //   this.zhang = 0
          var form = {}
          form.title = this.valueX
            if (this.valueX === '全部图片') {
              form.title = ''
            }
            const { data: res } = await this.$http.post(
            `goods/album/findImagesList?pageNo=${this.currentPage2}`, form);
            this.total2 = res.data.total
            res.data.rows.forEach(element => {
              this.tableData2.push(JSON.parse(element))
            });
      },
      async tests() {
        this.dialogFormVisible3 = true
        this.tableData2 = []
          var form = {}
          form.title = this.valueX
            if (this.valueX === '全部图片') {
              form.title = ''
            }
            const { data: res } = await this.$http.post(
            `goods/album/findImagesList?pageNo=${this.currentPage2}`, form);
            console.log(res)
            this.total2 = res.data.total
            res.data.rows.forEach(element => {
              this.tableData2.push(JSON.parse(element))
            });
      },
    // 设置商品图片为主图
    setZhuTu (index) {
      var tempOption = this.spuImageUrls[0]
      this.$set(this.spuImageUrls, 0, this.spuImageUrls[index])
      this.$set(this.spuImageUrls, index, tempOption)
    },
    // 删除商品图片
    deletedSpuImage (index) {
      this.spuImageUrls.splice(index, 1)
    },
    // 商品图片打开模态框
    openSpuImage () {
      this.spuDialogVisible = true
    },
    // 上一步
    topStep () {
      this.ruleForm.active = 2
      this.$emit('listenToChildEvent', this.ruleForm)
    },
    // 下一步  提交审核
    onSubmit () {
      this.paraItems = ""
      this.paraItems += '{'
      for (var a in this.editData) {
        this.paraItems += a + ':' + this.editData[a] + ','
      }
      this.paraItems = this.paraItems.substring(0, this.paraItems.length - 1)
      this.paraItems += '}'
      // 商品图片保存
      this.skuData.paraItems = this.paraItems
      this.skuData.spuImageUrls = this.spuImageUrls
      this.skuData.skus = this.skus
      this.skuData.specItems = JSON.stringify(this.specItems)
      this.nextStep()
    },
    // 返回到主页面 AddCommodity 提交审核
    nextStep () {
      // this.skuImageUrls.length <= 0 ||
      if (this.spuImageUrls.length <= 0) {
        this.$alert('商品图片必须上传,亲', '请上传图片', {
          confirmButtonText: '确定',
          callback: action => {
            this.$message({
              type: 'info',
              message: '请上传图片'
            });
          }
        });
      } else {
        console.log(this.skuData)
        this.ruleForm.active = 3
        this.$emit('sbumitGoods', this.skuData)
      }
    },
    handleAvatarSuccess1 (res, file) {
      this.skuImageUrl = file.response;
    },
    handleAvatarSuccess2 (res, file) {
      console.log(file)
      this.spuImageUrl = file.response;
    },
    // spu图片上传
    saveSpuImg () {
      this.skuData.spuImageUrl = this.spuImageUrl
      this.spuImageUrls.push(this.spuImageUrl)
      this.spuDialogVisible = false
      this.spuImageUrl = ""
    },
    // sku图片上传 窗口关闭
    saveImg () {
      this.skuImageUrls.push(this.skuImageUrl)
      this.sku.image = this.skuImageUrl
      this.skus.push(this.sku)
      this.sku.images = this.skuImageUrls.join(",")
      this.dialogVisible = false
      this.skuImageUrl = ""
    },
    beforeAvatarUpload (file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // spu对话框是否关闭
    handleClose2 (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.spuDialogVisible = false
          this.spuImageUrl = ""
          done();
        })
        .catch(_ => { });
    },
    // sku对话框是否关闭
    handleClose (done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          this.dialogVisible = false
          this.skuImageUrl = ""
          done();
        })
        .catch(_ => { });
    },
    // 图片上传初始化            初始化sku 他需要的值
    uploadPictures (index, row) {
      this.sku.name = this.ruleForm.name
      const obj = {}
      for (var prop in row) {
        this.sku.name += ' ' + row[prop] // SKU名称
        const key = prop
        const value = row[prop]
        if (!key === 'price' || key === 'alertNum' || key === 'num') {
          obj[key] = value
        }
      }
      this.sku.price = row.price
      this.sku.alertNum = row.alertNum // 库存预警数量
      this.sku.num = row.num // 库存数量
      // this.sku.categoryId = this.ruleForm.category3Id // 类目ID
      // this.sku.categoryMame = this.ruleForm.categoryMame // 类目名称
      //  this.sku.spec = obj
      // this.sku.price = this.step3Form.price // 价格
      // this.sku.alertNum = this.step3Form.alertNum // 库存预警数量
      // this.sku.num = this.step3Form.num // 库存数量
      this.sku.image = this.skuImageUrl // 商品图片
      this.sku.weight = 10 // 重量（克）
      this.sku.brandName = this.ruleForm.brandName // 品牌名称
      this.dialogVisible = true
    },
    // 清除表格
    dropTableData () {
      this.tableData = []
    },
    // 删除一个
    deletedTableData (index, rows) {
      this.tableData.splice(index, 1)
    },
    addTableColumn () {
      this.ary = []
      this.myary = []
      let count = 0 // 计数变量
      for (var prop in this.options) { // 因为不知道属性名 所以用这个 属性名是动态添加的 能获取到对象
        for (var prop2 in this.options[prop]) { // 因为不知道属性名 所以用这个 属性名是动态添加的 能获取到对象的属性名 就能循环了
          const value = []
          this.options[prop][prop2].forEach(element => {
            const key = prop2
            for (let i = 0; i <= this.checkdName.length; i++) {
              count = count + 1
              if (element === this.checkdName[i]) {
                value.push(element)
                this.hwtList.push(this.checkdName[i])
              } // 循环结束加值跟把数组初始化空
              if (this.checkdName.length === count) {
                this.ary.push(this.hwtList)
              }
            }
            this.specItems[key] = value // 给specItems赋值
          })
          this.hwtList = []
          count = 0
        }
      }
      if (this.ary.length !== 0) {
        if (this.ary.length > 1) {
          this.ary = this.calcDescartes(this.ary)
          // 计算笛卡尔积
          for (let i = 0; i < this.ary.length; i++) {
            const obj = {}
            for (let j = 0; j < this.ary[i].length; j++) {
              const prop = this.columns[j].prop
              obj[prop] = this.ary[i][j] // 为obj设置属性及属性值
              obj.price = 1
              obj.num = 1
              obj.alertNum = 1
            }
            this.myary.push(obj)
          }
        } else {
          for (let j = 0; j < this.ary[0].length; j++) {
            const obj = {}
            const prop = this.columns[0].prop
            obj[prop] = this.ary[0][j] // 为obj设置属性及属性值
            obj.price = 1
            obj.num = 1
            obj.alertNum = 1
            this.myary[j] = obj
          }
        }
      }
      this.tableData = this.myary
    },
    // 计算笛卡尔积
    calcDescartes (array) {
      if (array.length < 2) return array[0] || []
      return [].reduce.call(array, function (col, set) {
        var res = []
        col.forEach(function (c) {
          set.forEach(function (s) {
            var t = [].concat(Array.isArray(c) ? c : [c])
            t.push(s)
            res.push(t)
          })
        })
        return res
      })
    }
  },

  async created () {
    const { data: res } = await this.$http.get(`/goods/spu/initSpecAndPara?templateId=` + this.ruleForm.templateId)
    this.specs = res.data.specs
    this.paras = res.data.paras
    for (let i = 0; i < this.specs.length; i++) {
      const obj = {}
      const key = this.specs[i].name
      const value = this.specs[i].options.split(",")
      obj[key] = value
      this.options.push(obj)
      this.specs[i].checkList = value
      this.columns.push({ prop: this.specs[i].name, label: this.specs[i].name }) // 还没加prop 对应的属性名
    }
    for (let i = 0; i < this.paras.length; i++) {
      const obj = {}
      const key = this.paras[i].name
      const value = this.paras[i].options.split(",")
      obj[key] = value
      this.options2.push(obj)
      this.paras[i].checkList = value
    }
    this.getXianTitle()
  }
}
</script>

<style  scoped>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.hwtDiv {
  width: 240px;
  height: 330px;
  float: left;
}
.s51{
  margin-left: 37px;
  margin-top: 15px;
}
.image {
    width: 100%;
    display: block;
    height: 75px;
}
</style>
